#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <ctime>
using namespace std;
#include "RingQueue.hpp"
#include "Task.hpp"


struct ThreadData
{
    RingQueue<Task>* _rq;
    string _threadname;
};

void* Productor(void* args)
{
    //sleep(3);
    ThreadData* td = static_cast<ThreadData*>(args);
    while(true)
    {
        //1.获取数据
        int data1 = rand() % 10;
        usleep(10);
        int data2 = rand() % 5;
        char op = opers[rand() % 5];
        Task t(data1, data2, op);
        //2.生产数据
        td->_rq->Push(t);
        //cout << "Productor data done, data is : " << data << ", threadname : " << td->_threadname << endl;
        cout << "Productor send task: " << t.GetTask() << ", threadname : " << td->_threadname << endl;
        sleep(1);
    }
    return nullptr;
}
void* Consumer(void* args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    while(true)
    {
        //1.消费数据
        Task t;
        td->_rq->Pop(&t);
        //2.处理数据
        t();
        cout << "Consumer run task: " << t.GetTask() << ", task result: " << t.GetResult() << ", threadname : "  << td->_threadname << endl;
        //sleep(1);

    }
    return nullptr;
}

int main()
{
    srand(time(nullptr)^getpid());

    RingQueue<Task> *rq = new RingQueue<Task>(50);
    
    pthread_t c[5], p[3];

    for(int i = 0; i < 5; i++)
    {
        ThreadData* td = new ThreadData;
        td->_rq = rq;
        td->_threadname = "Productor-" + std::to_string(i);
        pthread_create(c + i, nullptr, Productor, td);
    }
    for(int i = 0; i < 3; i++)
    {  
        ThreadData* td = new ThreadData;
        td->_rq = rq;
        td->_threadname = "Consumer-" + std::to_string(i);
        pthread_create(p + i, nullptr, Consumer, td);
    }
    for(int i = 0; i < 5; i++)
    {
        pthread_join(c[i], nullptr);
    }
    for(int i = 0; i < 3; i++)
    {  
        pthread_join(p[i], nullptr);
    }
    return 0;
}